<template>
  <Form
    :model="searchForm"
    ref="formSearch"
    :rules="ruleValidate"
    slot="search-bar"
    label-position="left"
    :label-width="80"
    class="basicData-page ivu-form-no-margin-bottom"
    inline
  >
    <!-- 导出按钮 -->
    <Row :gutter="20" class="code-row-bg row-button">
      <!-- <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">&nbsp;</Col> -->
      <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
        <Form-item>
          <RPButton :text="$t('module.exportImport.export')" @click="exportData" />
        </Form-item>
      </Col>
    </Row>
    <!-- 选择框 -->
    <Row :gutter="32" class="code-row-bg row-select">
<!--       
      <template v-if="showSuperAdminRow">
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.tenant')">
              <Select
                v-model="searchForm.tenantId"
                style="width:200px"
                
                @on-change="onTenantChange"
                :clearable="true"
                :placeholder="$t('module.exportImport.entertenantCode')"
              >
                <Option
                  v-for="tenant in tenantList"
                  :value="tenant.tenantCode"
                  :key="tenant.id"
                >{{tenant.tenantName}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.product')">
              <Select
                v-model="searchForm.productId"
                style="width:200px"
                
                :clearable="true"
                :placeholder="$t('module.exportImport.enterProductCode')"
              >
                <Option
                  v-for="product in productList"
                  :value="product.productCode"
                  :key="product.productCode"
                >{{product.productName}}</Option>
              </Select>
            </Form-item>
          </Col>
      </template>
      <template v-else-if="showTenantAdminRow">
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.tenant')">
              <Select
                v-model="searchForm.tenantId"
                style="width:200px"
                
                :placeholder="$t('module.exportImport.entertenantCode')"
                disabled
              >
                <Option
                  v-for="tenant in tenantList"
                  :value="tenant.tenantCode"
                  :key="tenant.id"
                >{{tenant.tenantName}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.product')">
              <Select
                v-model="searchForm.productId"
                style="width:200px"
                
                :placeholder="$t('module.exportImport.enterProductCode')"
              >
                <Option
                  v-for="product in productList"
                  :value="product.productCode"
                  :key="product.productCode"
                >{{product.productName}}</Option>
              </Select>
            </Form-item>
          </Col>
      </template>
      <template v-else-if="showProductAdminRow">
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.product')">
              <Select v-model="searchForm.productId" style="width:200px"  disabled>
                <Option
                  v-for="product in productList"
                  :value="product.productCode"
                  :key="product.productCode"
                >{{product.productName}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.tenant')">
              <Select
                v-model="searchForm.tenantId"
                style="width:200px"
                
                :placeholder="$t('module.exportImport.entertenantCode')"
              >
                <Option
                  v-for="tenant in tenantList"
                  :value="tenant.tenantCode+'##'+tenant.clientId"
                  :key="tenant.id"
                >{{tenant.tenantName||tenant.tenantCode}}</Option>
              </Select>
            </Form-item>
          </Col>
      </template>
      <template v-else-if="showAppAdminRow">
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.product')">
              <Select v-model="searchForm.productId" style="width:200px"  disabled>
                <Option
                  v-for="product in productList"
                  :value="product.productCode"
                  :key="product.productCode"
                >{{product.productName}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
            <Form-item :label="$t('module.exportImport.tenant')">
              <Select
                v-model="searchForm.tenantId"
                style="width:200px"
                
                :placeholder="$t('module.exportImport.entertenantCode')"
                disabled
              >
                <Option
                  v-for="tenant in tenantList"
                  :value="tenant.tenantCode"
                  :key="tenant.id"
                >{{tenant.tenantName||tenant.tenantCode}}</Option>
              </Select>
            </Form-item>
          </Col>
      </template> -->
      <!-- 起始时间 -->
      <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
        <Form-item :label="$t('module.exportImport.startTime')" prop="startTime">
          <DatePicker
            v-model="searchForm.startTime"
            format="yyyy-MM-dd"
            type="date"
            :transfer="true"
             @on-change="onStartDateChange"
              :options="startDateOptions"
            :placeholder="$t('module.exportImport.selectStartTime')"
            style="width: 200px"
          ></DatePicker>
        </Form-item>
      </Col>
      <!-- 结束时间 -->
      <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
        <Form-item :label="$t('module.exportImport.endTime')" prop="endTime">
          <DatePicker
            v-model="searchForm.endTime"
            format="yyyy-MM-dd"
            type="date"
            :transfer="true"
             @on-change="onEndDateChange"
              :options="endDateOptions"
            :placeholder="$t('module.exportImport.selectEndTime')"
            style="width: 200px"
          ></DatePicker>
        </Form-item>
      </Col>
      <!-- 导出模块 -->
      <Col :xs="24" :sm="10" :md="10" :lg="8" :xxl="6" style="border:none;">
        <Form-item :label="$t('module.exportImport.modelName')" prop="modelCode">
          <Select v-model="searchForm.modelCode" style="width:200px">
            <Option
              v-for="model in modelList"
              :value="model.vsiDescription"
              :key="model.vsiKey"
            >{{model.vsiValue}}</Option>
          </Select>
        </Form-item>
      </Col>
    </Row>
  </Form>
</template>
<script>
import locales from "./locales.js";
// import { CoreModuleName } from "@/const.js";
import { findTenantList, listProductByTenantCode } from "@api/teantManageAPI";
import { GetItemValueByVsiId } from "@api/valuesetCodeApi";
import { GetTenantByCode, getApplicationByProductCode } from "@api/applicationApi";
// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  mixins: [locales],
  data() {
    return {
      showSuperAdminRow: false,
      showTenantAdminRow: false,
      showProductAdminRow: false,
      showAppAdminRow:false,
      tenantList: [],
      productList: [],
      searchForm: {
        modelCode: 1,
        tenantId: "",
        productId: "",
        startTime: "",
        endTime: "",
        appId: null
      },
      ruleValidate: {
        startTime: [
          { required: true, message: this.$t('module.exportImport.startTimeTips'), trigger: 'change' }
        ],
        endTime: [
          { required: true, message: this.$t('module.exportImport.endTimeTips'), trigger: 'change' }
        ],
      },
      modelList: []
    };
  },
  computed:{
    // modelList(){
    //   return  [
    //     {
    //       modelName: this.$t('module.exportImport.valueSet'),
    //       modelCode: 1
    //     },
    //     {
    //       modelName: this.$t('module.exportImport.function'),
    //       modelCode: 2
    //     },
    //     {
    //       modelName: this.$t('module.exportImport.resource'),
    //       modelCode: 3
    //     },
    //     {
    //       modelName: this.$t('module.exportImport.role'),
    //       modelCode: 4
    //     },
    //     {
    //       modelName: this.$t('module.exportImport.permissions'),
    //       modelCode: 5
    //     }
    //     // {
    //     //   modelName: this.$t('module.exportImport.post'),
    //     //   modelCode: 5
    //     // }
    //   ]
    // },
     startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.searchForm.endTime == "object" ) {
            // 日期是日期对象，如 new Date()
            return (
              // date &&
              // date.valueOf() < Date.now() - ONE_DAY &&
              // date.valueOf() > _this.searchForm.endTime.valueOf() - ONE_DAY
              date && date.valueOf() > _this.searchForm.endTime.valueOf() - ONE_DAY
            );
          } else if (typeof _this.searchForm.endTime == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.searchForm.endTime.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && date.valueOf() > endDate.valueOf();
            // return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          // return date && date.valueOf() < Date.now() - ONE_DAY;
          return date;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.searchForm.startTime == "object") {
            // 生效日期是日期对象，如 new Date()
            
            // debugger
            return date && date.valueOf() < _this.searchForm.startTime.valueOf() - ONE_DAY;
          } else if (typeof _this.searchForm.startTime == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.searchForm.startTime.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  created() {
    this.getBasicDataList()
    // const { currentPost } = $store.state[CoreModuleName];
    // const { tenantCode, productId, appId } = currentPost || {};
    // this.searchForm.appId = appId;
    // if (!tenantCode && !productId) {
    //   this.showSuperAdminRow = true;
    //   this.getTenantList();
    // } else if (productId && !tenantCode) {
    //   this.showProductAdminRow = true;
    //   this.searchForm.productId = productId;
    //   this.getProductByCode(productId);
    //   this.getTenantListByProductId(productId);
    // } else if (tenantCode && !productId) {
    //   this.showTenantAdminRow = true;
    //   this.searchForm.tenantId = tenantCode;
    //   this.getTenantByCode(tenantCode);
    //   this.getProductList(tenantCode);
    // } else if (tenantCode && productId) {
    //   this.showAppAdminRow = true;
    //   this.searchForm.productId = productId;
    //   this.searchForm.tenantId = tenantCode;
    //   this.getProductByCode(productId);
    //   this.getTenantByCode(tenantCode);
    // }
  },
  methods: {
    getBasicDataList () {
      $http.get(`${window.RPConfig.setting}/valueset/vsItem/list`, {vsCode: 'BASIC_DATA_TYPE'}).then((res) => {
        const rescords = res.data
        if (rescords.length) {
          this.searchForm.modelCode = rescords[0].vsiDescription
        }
        this.modelList = rescords
        
      });
    },
    exportData() {
      this.$refs["formSearch"].validate(valid => {
        if (valid) {
          const infoArray = [],
          searchInfo = Object.assign({}, this.searchForm);
          let tenantInfoArray = searchInfo.tenantId ? searchInfo.tenantId.split("##") : [];
          delete searchInfo.tenantId;
          searchInfo.tenantId = tenantInfoArray[0];
          searchInfo.appId = tenantInfoArray[1];
          // searchInfo.startTime = searchInfo.startTime && searchInfo.startTime;
          // searchInfo.endTime = searchInfo.endTime && searchInfo.endTime;
          delete searchInfo.modelCode;
          Object.keys(searchInfo).forEach(key => {
            searchInfo[key] && infoArray.push(`${key}=${searchInfo[key]}`);
          });

          // let apiPath;
          // switch (this.searchForm.modelCode) {
          //   case 1:
          //     apiPath = "setting/valueset";
          //     break;
          //   case 2:
          //     apiPath = "mgt/menu";
          //     break;
          //   case 3:
          //     apiPath = "mgt/resource";
          //     break;
          //   case 4:
          //     apiPath = "mgt/role";
          //     break;
          //   // case 5:
          //   //   apiPath = "mgt/post";
          //   //   break;
          //   case 5:
          //     apiPath = "mgt/datapolicy";
          //     break;
              
          // }

          $http
            .get(`/apis/${this.searchForm.modelCode}/exportExcel?` + infoArray.join("&"), null, null, { responseType: "blob" })
            .then(response => {
              const fileInfo = response.headers["content-disposition"].split(";")[1];
              let fileName = decodeURIComponent(fileInfo && fileInfo.split("=")["1"]);
              let blob = new Blob([response.data]);
              let href = window.URL.createObjectURL(blob); //创建下载的链接
              if (window.navigator.msSaveBlob) {
                try {
                  window.navigator.msSaveBlob(blob, fileName);
                } catch (e) {
                  console.error(e);
                }
              } else {
                // 谷歌浏览器 创建a标签 添加download属性下载
                let downloadElement = document.createElement("a");
                downloadElement.href = href;
                downloadElement.target = "_blank";
                downloadElement.download = fileName; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象
              }
          });
        }
      });
      
    },
    onTenantChange() {
      this.getProductList();
    },
    getProductList(tenantCode) {
      listProductByTenantCode(tenantCode || this.searchForm.tenantId).then(res => {
        this.productList = res.data;
        this.searchForm.productId = "";
      });
    },
    getTenantList() {
      findTenantList().then(res => {
        this.tenantList = res.data.records || [];
      });
    },
    getTenantListByProductId(productId) {
      getApplicationByProductCode(productId).then(res => {
        this.tenantList = res.data || [];
      });
    },
    getTenantByCode(tenantCode) {
      GetTenantByCode(tenantCode).then(({ data }) => {
        this.tenantList = [data];
      });
    },
    getProductByCode(productId) {
      GetItemValueByVsiId(productId).then(res => {
        this.productList = [{ productName: res.data, productCode: productId }];
      });
    },
    onStartDateChange(date) {
      this.searchForm.startTime = date;
    },
    onEndDateChange(date) {
      this.searchForm.endTime = date;
    }
  }
};
</script>